import React, { useEffect, useState , Key} from 'react'
import { Button, Form, Input, Table, Card , message , Tooltip } from 'antd';
import { SearchOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons"
import { useNavigate } from 'react-router-dom';

import style from './index.module.css'   //当前组件的专属样式

import {
  getHosSetListRequest,                  //查询
  deleteHosSetFromIdRequest,             //删除
  deleteAllHosSetFromIdsRequest          //批量删除
} from '@api/hospital/hospitalSet'       //引入Api请求

import type { getHosSetListRecordsType } from '@api/hospital/model/hospitalSetTypes' //引入数组的类型
import type { getHosSetListItemsType } from '@api/hospital/model/hospitalSetTypes' //引入数组Item的类型
import type { searchHosFinishParType } from "./types"  //引入查询医院函数形参的类型



export default function HospitalSet() {
  //使用编程式路由导航Hook 要写在组件的最外层
  const navigate = useNavigate()

  const [hospitalList, setHospitalList] = useState<getHosSetListRecordsType>([]) //数据
  const [total, setTotal] = useState(0)      //数据总条数
  const [current, setCurrent] = useState(1)   //当前页码
  const [pageSize, setPageSize] = useState(10) //每页条数
  const [isLoading, setIsLoading] = useState(false); //定义isLoading(table是否加载中)
  const [fieldValue , setFieldValue] = useState<searchHosFinishParType>({}) //点击查询获取输入框的内容
  
  const [deletee , setDeletee] = useState(true)  //控制删除后useEffect重新渲染
  const [isdisabled , setIsdisabled] = useState(true) //控制批量删除按钮的禁用和取消
  const [deleteallids , setDeleteAllids] = useState<Key[]>([]) //用状态保存点击选择框之后拿到的ids

  //刚加载组件的时候 或者当前页码和每页条数改变 就请求数据渲染页面
  //注意:异步函数不能作为useEffect的参数,因为useEffect可能会书写return一个函数起到清理作用,如果是异步函数,则return就是异步的了
  useEffect(() => {
    //在请求开始之前设置isLoading为true
    setIsLoading(true);

    //封装一个请求函数才可以,记得后续调用
    const getHosSetList = async () => {
      const result = await getHosSetListRequest({
        page: current,
        limit: pageSize,
        ...fieldValue
      })
      setHospitalList(result.records)   //得到的数据设置到页面
      setTotal(result.total)            //得到的数据总长度设置到页面

      //在请求结束之后设置isLoading为false
      setIsLoading(false);
    }
    getHosSetList();
  }, [current , pageSize , fieldValue , deletee])


  //第一行数据
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',  //dataIndex可以代替key
      width: 60,           //列的宽度
      align: "center" as "center",
      render(_: any, __: any, index: number) {
        return index + 1
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
      align: "center" as "center",
    },
    {
      title: '医院编号',
      dataIndex: 'hoscode',
      align: "center" as "center",
    },
    {
      title: 'api基础路径',
      dataIndex: 'apiUrl',
      align: "center" as "center",
    },
    {
      title: '签名',
      dataIndex: 'signKey',
      align: "center" as "center",
    },
    {
      title: '联系人姓名',
      dataIndex: 'contactsName',
      align: "center" as "center",
    },
    {
      title: '联系人手机',
      dataIndex: 'contactsPhone',
      align: "center" as "center",
    },
    {
      title: '操作',
      dataIndex: "do",
      width: 120,                  //列的宽度
      fixed: "right" as "right",    //固定最右边一列
      align: "center" as "center",
      render(_:any , data:getHosSetListItemsType) {
        const {id} = data  //拿到当前这一行数据对应的id传递给修改医院路由

        return (
          <div>
            <Tooltip title = {"修改医院"}>
              <Button 
                type='primary' 
                icon={<EditOutlined />} 
                className={style.mr} 
                //点击修改带着这条数据的id去修改页面
                onClick = {() => {navigate(`/syt/hospatil/updatehosset/${id}`);}}
              ></Button>
            </Tooltip>  

            <Tooltip title = {"删除医院"}>
              <Button 
                type='primary' 
                danger 
                icon={<DeleteOutlined />}
                //点击删除执行删除函数
                onClick = {reHosSetHandle(id)}
              ></Button>
            </Tooltip>

          </div >
        )
      }
    }
  ];


  //事件回调函数
  //1.页码或每页条数改变的回调
  const pageChangeHandle = (current:number , pageSize:number) => {
    //参数1 current:当前点击的页码  参数2 pageSize:每页条数
    //点击以后改变State , 就会发送请求重新渲染页面
    setCurrent(current)
    setPageSize(pageSize)
  }


  //2.点击查询的回调
  const searchHosFinishHandle = (fieldValue:searchHosFinishParType) => {
    //接收的形参就是输入框的内容根据name组成的对象 , 点击查询后把对象给fieldValue
    setFieldValue(fieldValue)
  }


  //3.点击添加医院的回调函数
  const addHosHandle = () => {
    //去添加医院页面
    navigate("/syt/hospatil/addhosset")
  }


  //5.点击删除的回调函数
  const reHosSetHandle = (id:number) => {
    return async () => {
      
      //发送删除医院请求
      await deleteHosSetFromIdRequest(id)
      
      //删除成功后重新渲染
      setDeletee(!deletee);

      //弹出删除成功提示
      message.success("删除医院成功!")

    }
  }


  //6.点击批量删除的回调函数
  const deleteAllHosSetHandle = async () => {

    //发送请求
    await deleteAllHosSetFromIdsRequest(deleteallids)    

    //删除成功后重新渲染
    setDeletee(!deletee);

    //弹出删除成功提示
    message.success("批量删除成功!")

    //把批量删除按钮改回禁用状态
    setIsdisabled(true)
    
  }

  //7.点击清空的回调函数
  const clearHandle = () => {
    //清空表单输入框状态中的内容重新渲染
    setFieldValue({})
  } 


  return (
    <div className={style.outer}>
      {/* 给整个组件最外层加一个卡片 */}
      <Card>

        <Form
          name="basic"
          wrapperCol={{ span: 30 }}
          layout='inline'
          onFinish={searchHosFinishHandle}
        >
          <Form.Item name="hosname">
            <Input placeholder="医院名称" />
          </Form.Item>

          <Form.Item name="hoscode">
            <Input placeholder='医院编号' />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
            <Button type="default" htmlType="reset" onClick = {clearHandle}>
              清空
            </Button>
          </Form.Item>

        </Form>

        <div className={style.mt}>
          <Button type='primary' className={style.mr} onClick = {addHosHandle}>添加</Button>
          <Button type="primary" danger disabled = {isdisabled} onClick = {deleteAllHosSetHandle}>批量删除</Button>
        </div>

        <Table
          columns={columns}        //列
          dataSource={hospitalList}  //每列数据
          className={style.mt}     //上边距
          scroll={{ x: 1300 }}     //横向滚动条长度
          bordered                 //边框
          //在table中 要求dataSource中有key属性,但是如果真的没有key 
          //则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"

          //页面加载动画
          loading={isLoading}

          //表格是否可选择(勾选框)
          rowSelection = {{
            //选中项发生变化时的回调 
            onChange(ids:Key[]){

              //只要选中后 ids.length大于0 取反就是false 批量删除的禁用状态就会解除
              setIsdisabled(!ids.length) // !ids.length => false

              //选择后把当前的ids存到状态中 等下发送批量删除请求要用到ids
              setDeleteAllids(ids)

            }
          }}

          //分页器
          pagination={{
            //当前页码
            current,
            //每页条数
            pageSize,
            //数据总条数
            total,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [1, 2, 3, 4, 5 , 6, 7 , 8 , 9 , 10],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,

            //数据总条数
            showTotal(total) {
              return `总数据有${total}条`
            },

            //当前页码或者每页条数改变就发请求重新渲染
            onChange: pageChangeHandle 

          }}

        />

      </Card>
    </div>
  )
}

